/**
 * 浏览历史相关接口
 */

import { getApiBaseUrl } from "@/utils/env";
import { getStorage } from "@/utils/storage";

const BASE_URL = getApiBaseUrl();

// 获取用户ID（从登录状态获取）
function getUserId() {
  const userId = getStorage('user_id');
  
  if (!userId) {
    throw new Error('请先登录');
  }
  
  return userId;
}

// 获取 token
function getToken() {
  const token = getStorage('user_token');
  return token || '';
}

/**
 * 添加浏览历史
 * @param {number} imageId 图片ID
 * @returns {Promise}
 */
export function addViewHistory(imageId) {
  return new Promise((resolve, reject) => {
    try {
      const userId = getUserId();
      const token = getToken();
      
      uni.request({
        url: `${BASE_URL}/api/history`,
        method: "POST",
        header: {
          'Authorization': `Bearer ${token}`,
          'X-User-Id': userId
        },
        data: {
          imageId: imageId,
          userId: userId
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const response = res.data;
            
            if (response && typeof response === 'object' && response.code === 200 && response.data) {
              resolve(response.data);
            } else if (response && typeof response === 'object') {
              resolve(response);
            } else {
              resolve({ success: true });
            }
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
}

/**
 * 删除浏览历史
 * @param {number} imageId 图片ID
 * @returns {Promise}
 */
export function removeViewHistory(imageId) {
  return new Promise((resolve, reject) => {
    try {
      const userId = getUserId();
      const token = getToken();
      
      uni.request({
        url: `${BASE_URL}/api/history/${imageId}`,
        method: "DELETE",
        header: {
          'Authorization': `Bearer ${token}`,
          'X-User-Id': userId
        },
        data: {
          userId: userId
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const response = res.data;
            
            if (response && typeof response === 'object' && response.code === 200 && response.data) {
              resolve(response.data);
            } else if (response && typeof response === 'object') {
              resolve(response);
            } else {
              resolve({ success: true });
            }
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
}

/**
 * 清空浏览历史
 * @returns {Promise}
 */
export function clearViewHistory() {
  return new Promise((resolve, reject) => {
    try {
      const userId = getUserId();
      const token = getToken();
      
      uni.request({
        url: `${BASE_URL}/api/history`,
        method: "DELETE",
        header: {
          'Authorization': `Bearer ${token}`,
          'X-User-Id': userId
        },
        data: {
          userId: userId
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const response = res.data;
            
            if (response && typeof response === 'object' && response.code === 200 && response.data) {
              resolve(response.data);
            } else if (response && typeof response === 'object') {
              resolve(response);
            } else {
              resolve({ success: true });
            }
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
}

/**
 * 获取用户浏览历史列表
 * @param {Object} params 请求参数
 * @param {number} params.page 页码
 * @param {number} params.pageSize 每页数量
 * @returns {Promise}
 */
export function getViewHistoryList(params = {}) {
  return new Promise((resolve, reject) => {
    try {
      const userId = getUserId();
      const token = getToken();
      
      uni.request({
        url: `${BASE_URL}/api/history`,
        method: "GET",
        header: {
          'Authorization': `Bearer ${token}`,
          'X-User-Id': userId
        },
        data: {
          page: params.page || 1,
          pageSize: params.pageSize || 20,
          userId: userId
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const response = res.data;
            
            if (response && typeof response === 'object' && response.code === 200 && response.data) {
              resolve({
                code: 200,
                data: response.data
              });
            } else if (response && typeof response === 'object' && response.list !== undefined) {
              resolve({
                code: 200,
                data: response
              });
            } else {
              resolve({
                code: 200,
                data: response
              });
            }
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
}

